<?php

class M_users extends CI_Model {

	function __construct(){
		parent::__construct();
	}

	function users_list($search_text, $start, $end){

		$sql="SELECT
				users.id,
				group_id,
				username,
				group_name,
				email,
				fullname,
				handphone,
				last_login_date
			FROM
				users
			LEFT JOIN groups ON (users.group_id = groups.id)
			WHERE users.id IS NOT NULL
			";
		if($search_text != ''){
			$sql .= " 
				AND ( lower(username) LIKE '%".$search_text."%' 
				OR lower(email) LIKE '%".$search_text."%' 
				OR lower(fullname) LIKE '%".$search_text."%' 
				)
			";
		}
		$num_rows = $this->m_public_function->get_count_rows($sql);
		if($start != 0 && $end != 0){
			$sql.=" LIMIT $start, $end";
		}
		$query = $this->db->query($sql);

		if($num_rows > 0){
			$result = $query->result();
			$i = 0;
			foreach($result as $row){
				$data[$i] = $row;
				$i++;
			}
		}
		$final[] = array(
			"TotalRows"=>$num_rows,
			"results"=>$data
		);
		return json_encode($final);
	}

	function getDetail($id){
		$sql = "
			SELECT
				users.id,
				group_id,
				group_name,
				username,
				`password`,
				fullname,
				email,
				handphone
			FROM users
			JOIN groups ON users.group_id = groups.id
			WHERE users.id = ".$id."
		";
		$query = $this->db->query($sql);
		$num_rows = $query->num_rows();
		if($num_rows > 0){
			return $query->row();
		}
	}
	
	function users_save($params){
		extract($params);
		if($task == 'create'){
			$this->db->insert('users',$data);
		}else{
			$this->db->where('id', $id);
			$this->db->update('users',$data);
		}
		if($this->db->affected_rows()){
			return 1;
		}else{
			return 0;
		}
	}

	function users_delete($id){
		$this->db->where('id',$id);
		$this->db->delete('users');
		if($this->db->affected_rows()){
			return 1;
		}else{
			return 0;
		}
	}
}